

<body>

	<div class="hd ">
		<div class="warp">
			<ul class="btn-list">
				<li class="item">

					<a href="<?php echo $base_url?>home/order/shoppingcar" class="shop-car bg">
						<!--<div class="num">1</div>-->
						<i class="icon iconfont icon-icon"></i>
					</a>
				</li>
				<li class="item">
					<!--<a href="./register.html">
                        <i class="iconfont icon-wode"></i>请登录
                    </a>-->
					<?php if(isset($user)){?>
					<span href="#" class="bg">
                        <i class="icon iconfont icon-wode"></i><?php echo $user->mobile;?>
                    </span>
                    
                    <ul class="child-item">
                            <li><a href="<?php echo $base_url?>home/order/userorders">我的订单</a></li>
                            <li><a href="<?php echo $base_url?>home/address">收货地址</a></li>
                            <li><a href="<?php echo $base_url;?><?php if(!empty($cardid)){echo 'home/card/cardlist';}else{echo 'home/card/addcard';}?>">绑定银行卡</a></li>
                            <li><a href="<?php echo $base_url?>home/account/logout">退出商城</a></li>
                    </ul>
                    <?php }else{?>
                    <a href="<?php echo $base_url?>home/account/login?back_url=<?php echo urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); ?>">

                        <i class="iconfont icon-wode"></i>请登录
                    </a>
					<?php }?>
				</li>
			</ul>
			<a href="<?php echo $base_url?>home/goods/index">
            <img src="<?php echo $base_url?>static/dist/images/logo.png" alt="" class="logo-img">
             <span class="span_txt">商城首页</span>
            </a>
		</div>
	</div>



	<div class="shop_car_list">
		<div class="warp">
			<div class="p_tit">
				我的购物车(<span>0</span>件商品)
			</div>
			<div class="data-list">
				<div class="tab_warp">
					<div class="tit">
						<div class="td td_1">
							<div class="icon-check">
								<i class="iconfont icon-duoxuan"></i>
							</div>
							<span>全部</span>
						</div>
						<div class="td td_2">
							商品信息
						</div>
						<div class="td td_3">&nbsp;</div>
						<div class="td td_4">单价</div>
						<div class="td td_5">数量</div>
						<div class="td td_6">金额</div>
						<div class="td td_7">操作</div>
					</div>


				</div>
			</div>


			<div class="settlement-bar">

				<div class="r">
					合计<span class="price">
                        <span>¥</span>0.00
					</span>
					<a class="sub_btn">
                        去结算
                    </a>
				</div>
				<p class="msg">
					已选商品<span class="num">0</span>件
				</p>
			</div>
		</div>
	</div>


	<script src="<?php echo $base_url?>static/dist/js/lib/jquery.min.js"></script>
	<!--<script src="<?php echo $base_url?>static/dist/js/lib/store.legacy.min.js"></script>-->
	<script>
	

		//购物车
		$(function () {
			// var cartData = store.get('cartData') || [];
			var cartData = getCookie('cartData') || [];

			if (cartData.length != 0) {
				fillCart();
			}

			function fillCart() {
				var htmlStr = '';
				var sum = 0, num = 0;
				for (var i = 0; i < cartData.length; i++) {
					num = parseInt(cartData[i].quantity) || 0;
					if (num) {
						sum += num;
					}
				}
				if (sum >= 100) {
					sum = '99+'
				}
				if(sum == 0){
					 $('.shop-car').find('.num').addClass('none');
					 
					 return;
				}
				htmlStr = '<div class="num">' + sum + '</div>';
				$numEl = $('.shop-car .num');
				if ($numEl.length == 0) {
					$('.shop-car').append(htmlStr)
				} else {
					$numEl.html(sum)
				}
			}

			// var cart = store.get('cartData') || [];

			var total_price = 0;
			var html = "";

			if (cartData.length > 0) {
					
					$.ajax({
						url:"<?php echo $base_url;?>ajax/goods/getDetail",
						type:'POST',
						data:{'cartData':cartData},
						dataType:'json',
						success:function(result){
							var effect =  result.data.effect,
							noeffect = result.data.noeffect;
							html = "";
							if(effect.length > 0){
								for(var i=0;i<effect.length;i++){

									html += '<div class="tr" data-effect="1" data-price="' + effect[i]['price'] + '" data-id="' + effect[i]['goods_id'] + '">' +
											'<div class="td td_1">' +
											'<div class="icon-check"><i class="iconfont icon-duoxuan"></i></div>' +
											'</div>' +
											'<div class="td td_2">' +
											'<div class="l_img"><img src="<?php echo $base_url;?>static/upload/goods/' + effect[i]['img_path'] + '" alt="' + effect[i]['img_name'] + '">' +
											'</div>' +
											'<div class="r_msg"><p class="name">' + effect[i]['name'] + '</p><p class="msg">' + effect[i]['other_name'] + '</p></div>' +
											'</div>' +
											'<div class="td td_3"><p class="sku_txt"></p></div><div class="td td_4"><p class="price"> <span>¥</span>' + effect[i]['price'] + '</p></div>' +
											'<div class="td td_5">' +
											'<div class="num-js"><a href="#1" class="sub"><i class="iconfont icon-jian"></i></a><input type="number" value="' + effect[i]['amount'] + '" class="val_num" autocomplete="off"><a href="#2" class="add"><i class="iconfont icon-jia"></i></a></div>' +
											'</div>' +
											'<div class="td td_6"><p class="price2"> <span>¥</span>' + effect[i]['total_price'] + '</p></div><div class="td td_7"><a href="#111" class="del_tr">删除</a></div>' +
											'</div>';
								}
							}
							if(noeffect.length > 0){
								for(var i=0;i<noeffect.length;i++){
								    
									html += '<div class="tr sx" data-effect="0" data-price="' + noeffect[i]['price'] + '" data-id="' + noeffect[i]['goods_id'] + '">' +
											'<div class="td td_1">' +
											'<span class="sx-icon">失效</span>' +
											'</div>' +
											'<div class="td td_2">' +
											'<div class="l_img"><img src="<?php echo $base_url;?>static/upload/goods/' + noeffect[i]['img_path'] + '" alt="' + noeffect[i]['img_name'] + '">' +
											'</div>' +
											'<div class="r_msg"><p class="name">' + noeffect[i]['name'] + '</p><p class="msg">' + noeffect[i]['other_name'] + '</p></div>' +
											'</div>' +
											'<div class="td td_3"><p class="sku_txt"></p></div><div class="td td_4"><p class="price"> <span>¥</span>' + noeffect[i]['price'] + '</p></div>' +
											'<div class="td td_5">' +
											'<div class="num-js"><a href="#1" class="sub"><i class="iconfont icon-jian"></i></a><input type="number" value="' + noeffect[i]['amount'] + '" class="val_num" autocomplete="off"><a href="#2" class="add"><i class="iconfont icon-jia"></i></a></div>' +
											'</div>' +
											'<div class="td td_6"><p class="price2"> <span>¥</span>' + noeffect[i]['total_price'] + '</p></div><div class="td td_7"><a href="#111" class="del_tr">删除</a></div>' +
											'</div>';
								}
							}
							
							for(var i=0;i<effect.length;i++){			
								upCartData(effect[i]['goods_id'], 'price', effect[i]['price']);
								setCookie('cartData',cartData,2)		
							}
							$(".tab_warp").append(html);
						}

					})
					
				
			} else {

				$(".shop_car_list").remove();
				html = '<div class="no_car"><img src="<?php echo $base_url?>static/dist/images/nonecar2.jpg" alt=""></div>';
				$(".hd").after(html);
				//$(".sub-order-ft").css('display','none');//不显示底边栏
			}


			//+
			$('body').on('click', '.add', function () {
				var $this = $(this);
				var $valNum = $this.parents('.num-js').find('.val_num');
				var num = parseInt($valNum.val()) || 1;
				num++;
				$valNum.val(num);
				fillTrData($this, num);
				fillStor($this, num);
				var isActive = $this.parents('.tr').find('.icon-check').hasClass('active');
				if(isActive){					
					sumPriceFn();
					// var tmpCartData = [];
					// $('.tr').find('.icon-check.active').each(function(i,el){
					// 	var goodsId = $(el).parents('.tr').data('id');
					// 	var curData = getCartData(goodsId);
					// 	tmpCartData.push(curData);
					// })

					// var tmp = 0;
					// for(var i = 0;i <tmpCartData.length;i++){
					// 	var price = parseFloat(tmpCartData[i].price) || 0;
					// 	var quantity = parseInt(tmpCartData[i].quantity) || 1;
					// 	tmp+=price*quantity
					// }
					// sumPrice = tmp;	
					// upSumPrice(sumPrice)
				}
				updataTit();
			})
			//-
			$('body').on('click', '.sub', function () {
				var $this = $(this);
				var $valNum = $this.parents('.num-js').find('.val_num');
				var num = parseInt($valNum.val()) || 1;
				num = num > 1 ? num - 1 : 1;
				$valNum.val(num);
				fillTrData($this, num)
				fillStor($this, num);
				var isActive = $this.parents('.tr').find('.icon-check').hasClass('active');				
				if(isActive){					
					sumPriceFn();
				}
				updataTit();
			})

			$('body').on('blur', '.val_num', function () {
				// console.log('失去焦点');
				var $this = $(this);
				var num = parseInt($this.val()) || 1
				num = num > 1 ? num : 1;
				// num<1?$(this).val(1):$(this).val(num);			
				num = num > 100000 ? 100000 : num
				$this.val(num)
				fillTrData($this, num)
				fillStor($this, num);
				var isActive = $this.parents('.tr').find('.icon-check').hasClass('active');				
				if(isActive){					
					sumPriceFn();
				}
				updataTit();
			})

			//删除
			$('body').on('click','.del_tr',function(){
				var $this = $(this);
				var $tr = $this.parents('.tr');
				$tr.remove();
				// console.log(cartData)				
				delCartData($tr.data('id'));
				// console.log(cartData)
				// store.set('cartData', cartData);
				setCookie('cartData',cartData,2)
				checkActive();
				updataTit();
				sumPriceFn();
				fillCart()
			})
			//计算总金额
			function sumPriceFn(){
				var tmpCartData = [];
				$('.tr').find('.icon-check.active').each(function(i,el){
					var goodsId = $(el).parents('.tr').data('id');
					var curData = getCartData(goodsId);
					tmpCartData.push(curData);
				})

				var tmp = 0;
				for(var i = 0;i <tmpCartData.length;i++){
					var price = parseFloat(tmpCartData[i].price) || 0;
					var quantity = parseInt(tmpCartData[i].quantity) || 1;
					tmp+=price*quantity
				}
				sumPrice = tmp;	
				upSumPrice(sumPrice)
			}

			//计算每行金额
			function sumTrData($this, num){
				var $tr = $this.parents('.tr');
				var price = parseFloat($tr.data('price')) || 0
				var sumPrice = parseFloat(price * num) || '--'
				// if (typeof sumPrice == 'number') {
				// 	sumPrice = sumPrice.toFixed(2);
				// }
				return sumPrice
			}
			//填充每行金额数据
			function fillTrData($this, num) {
				var $tr = $this.parents('.tr');
				var $price2El = $tr.find('.price2')
				var price = parseFloat($tr.data('price')) || 0
				var sumPrice = parseFloat(price * num) || '--'
				if (typeof sumPrice == 'number') {
					sumPrice = sumPrice.toFixed(2);
				}
				$price2El.html('<span>¥</span>' + sumPrice);
			}
			//更新动作
			function fillStor($this, num) {
				var $tr = $this.parents('.tr');
				var goodsId = $tr.data('id');
				// console.log(num);
				// console.log(getCartData(goodsId));
				var curData = getCartData(goodsId)
				if (curData) {
					upCartData(goodsId, 'quantity', num);
					// store.set('cartData', cartData);
					setCookie('cartData',cartData,2)
					fillCart()
				}

			}

			//更新内部cartData对象
			function upCartData(id, key, val) {
				for (var i = 0; i < cartData.length; i++) {
					if (cartData[i].id == id) {
						cartData[i][key] = val;
					}
				}
			}
			//获取sort数据
			function getCartData(id) {
				var res = null;
				for (var i = 0; i < cartData.length; i++) {
					if (cartData[i].id == id) {
						res = cartData[i];
					}
				}
				return res;
			}
			//删除cartData对象
			function delCartData(id){
				var curData = null
				for (var i = 0; i < cartData.length; i++) {
					if (cartData[i].id == id) {
						curData = cartData[i]
					}
				}
				
				cartData.splice(cartData.indexOf(curData),1) 
			}

			var sumPrice = 0;
			$('body').on('click', '.icon-check', function () {
				var $this = $(this);
				var isActive = $this.hasClass("active");
				var isAll = !!$(this).parents('.tit').length;
				var activeLen = $('.tr').find('.icon-check').length;
				
				if (isAll) {
					isActive ? $('.data-list').find('.icon-check').removeClass('active') : $('.data-list').find('.icon-check').addClass('active')
				} else {
					isActive ? $this.removeClass('active') : $this.addClass('active');
					if (activeLen == $('.tr').find('.active').length) {
						$('.tit').find('.icon-check').addClass('active');
					} else {
						$('.tit').find('.icon-check').removeClass('active');
					}
					
				}
				var $tr = $this.parents('.tr');	
				var goodsId = $tr.data('id');
				var curData = getCartData(goodsId);					
				if(!isAll){
					var curQuantity = parseInt(curData.quantity) || 1;
					if(isActive){												
						sumPrice-=sumTrData($this,curQuantity);
					}else{									
						sumPrice+=sumTrData($this,curQuantity);
					}
				}else{
					if(isActive){
						sumPrice = 0;
					}else{							
						// sumPrice+=sumTrData($this,$tr.find('.val_num').val());
						var tmp = 0;						
						for(var i = 0;i <cartData.length;i++){						
							if($('.tr[data-id="'+cartData[i].id+'"]').data('effect')=='1'){
								var price = parseFloat(cartData[i].price) || 0;
								var quantity = parseInt(cartData[i].quantity) || 1;
								tmp+=price*quantity
							}
						}
						sumPrice = tmp;						
					}
				}
				
				upSumPrice(sumPrice)

				
				checkActive();

			})
			function checkActive() {
				var $settlementBar = $('.settlement-bar');
				var activeLen = $('.tr').find('.active').length;
				if (activeLen != 0) {
					$settlementBar.addClass('active');
					// $settlementBar.find('.msg .num').text(activeLen)
				} else {
					$settlementBar.removeClass('active');
					// $settlementBar.find('.msg .num').text('0')
				}
			}
			checkActive();
			updataTit();
			function updataTit(){
				var sumTmp = 0;
				for(var i=0;i<cartData.length;i++){
					sumTmp += cartData[i].quantity
				}
				$('.shop_car_list').find('.p_tit span').html(sumTmp)
			}
			
			function upSumPrice(sum){
				sum = sum.toFixed(2);
				$(".settlement-bar").find('.price').html('<span>¥</span>'+sum)
				var sl = 0;
				$('.tr').find('.icon-check.active').each(function(i,el){
					sl +=parseInt($(el).parents('.tr').find('.val_num').val());
				})
				$(".settlement-bar").find('.msg .num').html(sl)
			}


		})


	</script>
    <script>
        $(function(){
            $(".sub_btn").click(function(){
				if(!$(this).parents('.settlement-bar').hasClass('active')){
					alert('至少选择一件商品');
					return false;
				}
                var selArr=[];
                $(".tr").find(".icon-check.active").each(function(i, item){
                    var selObj = {};
                    selObj.goods_id = $(item).parents(".tr").data("id");                    
                    selObj.quantity = $(item).parents(".tr").find(".num-js .val_num").val()
                    selArr.push(selObj);
                })
                if(selArr.length <= 0)
                {
                    alert('请选择至少一件商品');
                }
                else
                {
                    location.href = "<?php echo $base_url;?>home/order/submitorder?data=" + encodeURI(JSON.stringify(selArr));
                }
            });
        });

		function setCookie(cname, cvalue, exdays) {
			cvalue = JSON.stringify(cvalue)

			var d = new Date();
			d.setTime(d.getTime() + (exdays*60*60*1000));
			var expires = "expires="+d.toUTCString();
			document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";  
		}
        function getCookie(cname) {
			var name = cname + "=";
			var ca = document.cookie.split(';');
			for(var i=0; i<ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1);
				if (c.indexOf(name) != -1){
					return JSON.parse(c.substring(name.length, c.length));
				} 
			}
			return "";
		}
    </script>
</body>

</html>
